package com.yzt.zhuju.widget

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.RelativeLayout
import androidx.annotation.DrawableRes
import androidx.fragment.app.FragmentActivity
import  com.yzt.zhuju.databinding.BaseLayoutTitlebarBinding

/**
 * @Desc  自定义titlebar
 * @Author macjay
 * @Time 2022/12/19 17:42
 */
class MCTitlebar : RelativeLayout {
    private lateinit var viewBinding: BaseLayoutTitlebarBinding

    constructor(context: Context?) : super(context) {
        init(context)
    }

    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
        init(context)
    }

    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        init(context)
    }

    private fun init(context: Context?) {
        viewBinding = BaseLayoutTitlebarBinding.inflate(LayoutInflater.from(context), this, true)
        viewBinding.baseIvBack.setOnClickListener { (context as? FragmentActivity)?.onBackPressed() }
    }

    fun setLeftAction(listener: OnClickListener?) {
        viewBinding.baseIvBack.setOnClickListener { listener?.onClick(it) }
    }

    fun setTitle(title: String?, listener: OnClickListener? = null) {
        viewBinding.baseTvTitle.text = title ?: ""
        viewBinding.baseTvTitle.setOnClickListener { listener?.onClick(it) }
    }

    fun setRightIcon1Action(@DrawableRes resId: Int, listener: OnClickListener?) {
        viewBinding.baseIvRight1.setImageResource(resId)
        viewBinding.baseIvRight1.setOnClickListener { listener?.onClick(it) }
    }

    fun setRightIcon(@DrawableRes resId: Int) {
        viewBinding.baseIvRight1.setImageResource(resId)
    }

    fun setRightAction(listener: OnClickListener?) {
        viewBinding.baseIvRight1.setOnClickListener { listener?.onClick(it) }
    }

    fun setRightIcon2Action(@DrawableRes resId: Int, listener: OnClickListener?) {
        viewBinding.baseIvRight2.setImageResource(resId)
        viewBinding.baseIvRight2.setOnClickListener { listener?.onClick(it) }
    }

    fun setRightTextAction(content: String?, listener: OnClickListener?) {
        viewBinding.baseTvRight.visibility =
            if (content.isNullOrEmpty()) View.GONE else View.VISIBLE
        viewBinding.baseTvRight.text = content ?: ""
        viewBinding.baseTvRight.setOnClickListener {
            listener?.onClick(it)
        }
    }
}